## APP SETUP ##
express = require 'express'
path = require 'path'
app = express()
rootDir = path.dirname(process.mainModule.filename)

app.configure () ->
    app.set "views", "#{rootDir}/private/views"
    app.set "view engine", "jade"

    ## STATIC CONTENT MIDDLEWARE ##
    app.use express.static("#{rootDir}/public")
    
    ## COOKIE PARSER MIDDLEWARE ##
    app.use express.cookieParser()
    
    ## SESSION MIDDLEWARE ##
    app.use express.session ({secret: '1234567890QWERTY'})

    ## AUTHENTICATION MIDDLEWARE ##
    app.use (req, res, next) ->
        loginRequested = req.url is "/login"

        if req.session.user
            if loginRequested
                res.redirect('/')
                return false
        else if not loginRequested
            res.redirect('/login')
            return false
    
        next()
        return true

    app.use express.bodyParser()
    
    ### COMMON PROPERTIES MIDDLEWARE ###
    app.use (req, res, next) ->
        res.locals.user = req.session.user
        next()
        return
    
    app.use app.router

    ## MISSING RESOURCE MIDDLEWARE ##
    app.use (req, res) ->
        console.log "Missing resource was requested..."
        res.render 'error/404'

    ## ERROR HANDLING MIDDLEWARE ##
    app.use (err, req, res, next) ->
        console.log err.message
    
    return

module.exports = app